<template>
  <div
    class="tui-conversation custom-tui-conversation"
    @click="handleClickConv"
    @touchstart="handleTouchStart"
    @touchend="handleTouchEnd"
  >
    <!-- <ConversationHeader ref="headerRef" /> -->
    <!-- <ConversationNetwork /> -->
	
	<view class="custom-navbar display-flex just-between">
		<view class="custom-navbar-left">
			<view class="display-flex">
				<view class="listtxt">
					聊天列表
				</view>
				<view class="top" style="margin-left: 15rpx;" v-if="loginState">
					<block v-if="userInfo.is_line == 1">
						<view class="dian"></view>
						<view class="txt">
							在线
						</view>
					</block>
					<block v-else>
						<view class="dian2"></view>
						<view class="txt2">
							{{userInfo.line_time_str}}
						</view>
					</block>
				</view>
			</view>
		</view>
		<!-- <image src="https://cdnauth.dreamyuewen.com/images/clear.png" mode="aspectFit" style="width: 36rpx;height: 36rpx;" @tap="clearRead"></image> -->
	</view>
	
	<!-- <view class="" style="padding: 0 30rpx;">
		<view class="serbox">
			<image :src="'/images/search.png' | formatImgUrl" class="serpic" mode=""></image>
			<input type="text" class="serput" placeholder="搜索联系人、聊天记录" v-model="searchVal" @confirm='startSearch'>
		</view>
	</view> -->
	
	<block v-if="loginState">
		<ConversationList
		  class="tui-conversation-list"
		  ref="conversationListDomRef"
		  @handleSwitchConversation="handleSwitchConversation"
		  @getPassingRef="getPassingRef"
		/>
	</block>
	<view class="empytView" v-else>
		<image :src="'/images/kong.png' | formatImgUrl" mode="widthFix" />
	</view>
	
	<!-- <view class="tabbar">
		<view class="tabbar-item" @click="tabbarChange('/pages/index/index')">
			<image class="item-img1" src="/static/images/ta.png"></image>
			<view class="itemtxt">
				首页
			</view>
		</view>
		<view class="tabbar-item" @click="tabbarChange('/pages/find/find')">
			<image class="item-img1" src="/static/images/tb.png"></image>
			<view class="itemtxt">
				发现
			</view>
		</view>
		<view class="tabbar-item" @click="tabbarChange('pages/resease/resease')">
			<image class="item-img1" src="/static/images/fa.png"></image>
			<view class="itemtxt"></view>
		</view>
		
		<view class="tabbar-item">
			<image class="item-img" src="/static/images/tca.png" ></image>
			<view class="itemtxt tabbarActive">
				消息
			</view>
		</view>
		
		<view class="tabbar-item" @click="tabbarChange('/pages/user/user')">
			<image class="item-img1" src="/static/images/td.png"></image>
			<view class="itemtxt">
				我的
			</view>
		</view>
	</view> -->
  </div>
</template> 

<script lang="ts" setup>
import * as db from '@/common/db.js'

import {
  TUIStore,
  TUIGlobal,
  StoreName,
  TUIChatService
} from "@tencentcloud/chat-uikit-engine";
import { ref } from "../../adapter-vue";
import ConversationList from "./conversation-list/index.vue";
import ConversationHeader from "./conversation-header/index.vue";
import ConversationNetwork from "./conversation-network/index.vue";
import { onHide,onShow } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
const emits = defineEmits(["handleSwitchConversation"]);

const totalUnreadCount = ref(0);
const headerRef = ref<HTMLElement | undefined>();
const conversationListDomRef = ref<HTMLElement | undefined>();
const touchX = ref<number>(0);
const touchY = ref<number>(0);

TUIStore.watch(StoreName.CONV, {
  totalUnreadCount: (count: number) => {
    totalUnreadCount.value = count;
  },
});

var searchVal = '';

import * as Db from '@/common/db.js'
const userInfo = Db.get('userInfo')

let paddingBottomHeight = 0;
uni.getSystemInfo({
	success: function(res) {
		let model = ['X', 'XR', 'XS', '11', '12', '13', '14', '15'];
		model.forEach(item => {
			if (res.model.indexOf(item) != -1 && res.model.indexOf('iPhone') != -1) {
				paddingBottomHeight = 40;
			}
		})
	}
});
console.log(paddingBottomHeight);

const handleSwitchConversation = (conversationID: string) => {
  TUIGlobal?.global?.navigateTo({
    url: "/TUIKit/components/TUIChat/index",
  });
  emits("handleSwitchConversation", conversationID);
};

const closeChildren = () => {
  headerRef?.value?.closeChildren();
  conversationListDomRef?.value?.closeChildren();
};

const handleClickConv = () => {
  closeChildren();
};

const loginState = ref<number>(1);

// var loginState;
onHide(closeChildren);
onShow(()=>{
	console.log(321,db.get('auth'))
	loginState.value = uni.getStorageSync('loginState') || '';
	
	conversationListDomRef.value?.updatelist()
})




// const loginState = getApp().getTest()
// console.log(loginState,987);

const handleTouchStart = (e: any) => {
  touchX.value = e.changedTouches[0].clientX;
  touchY.value = e.changedTouches[0].clientY;
};

const handleTouchEnd = (e: any) => {
  let x = e.changedTouches[0].clientX;
  let y = e.changedTouches[0].clientY;
  let turn = "";
  if (x - touchX.value > 50 && Math.abs(y - touchY.value) < 50) {
    //右滑
    turn = "right";
  } else if (x - touchX.value < -50 && Math.abs(y - touchY.value) < 50) {
    //左滑
    turn = "left";
  }
  if (y - touchY.value > 50 && Math.abs(x - touchX.value) < 50) {
    //下滑
    turn = "down";
  } else if (y - touchY.value < -50 && Math.abs(x - touchX.value) < 50) {
    //上滑
    turn = "up";
  }
  //根据方向进行操作
  if (turn === "down" || turn === "up") {
    closeChildren();
  }
};

const getPassingRef = (ref) => {
	ref.value = conversationListDomRef.value;
}

const tabbarChange = (url) => {
  if(url != "/pages/resease/resease"){
  	//记录？
  	uni.setStorageSync("end_path",url);
  	
  }
  
  uni.redirectTo({
  	url: url
  })
};

const startSearch = () => {
  
  let promise = TUIChatService.searchCloudMessages({
     keywordList: [searchVal],
     timePosition: Number((new Date().getTime()/1000).toFixed(0)),
     timePeriod: 24 * 60 * 60,
  });
  console.log(searchVal,promise,111)
  promise.then(function(imResponse) {
   // 搜索消息成功
     const { totalCount, cursor,searchResultList } = imResponse.data;
     console.log(totalCount); // 满足搜索条件的消息所在的所有会话总数量
     console.log(cursor); // 下一次云端搜索的起始位置, 如果没有表示搜索结果拉取完成
     console.log(searchResultList); // 满足搜索条件的消息根据会话 ID 分组，分页返回分组结果
     for (let i = 0; i < searchResultList.length; i++) {
        const searchResultItem = searchResultList[i];
        const { conversationID, messageCount, messageList } = searchResultItem;
        console.log(conversationID); // 会话 ID
        console.log(messageCount); // 当前会话一共搜索到了多少条符合要求的消息
        // 本次搜索【全部会话】，那么 messageList 中装载的消息条数会有如下两种可能：
        // - 如果某个会话中匹配到的消息条数 > 1，则 messageList 为空，您可以在 UI 上显示“ messageCount 条相关记录”。
        // - 如果某个会话中匹配到的消息条数 = 1，则 messageList 为匹配到的那条消息，您可以在 UI 上显示之，并高亮匹配关键词。
        console.log(messageList);
      }
  }).catch(function(imError) {
     console.error(imError); // 搜索消息失败
  });
};

const clearRead= ()=>{
	let promise = TUIChatService.setAllMessageRead();
	promise.then(function(imResponse) {
	  // 已读上报成功，所有会话的 unreadCount 属性值被置为0
	}).catch(function(imError) {
	  // 已读上报失败
	  console.warn('setAllMessageRead error:', imError);
	});
};
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style scoped lang="scss">
	.custom-tui-conversation{
		padding-top: calc(var(--status-bar-height) + var(--window-top) + 50px);
		
		.serbox {
			display: flex;
			align-items: center;
			background: #F8F8F8;
			border-radius: 142px;
			height: 72rpx;
			padding: 0 26.66rpx;
			margin-bottom: 20rpx;
		
			.serpic {
				width: 32rpx;
				height: 32rpx;
				flex-shrink: 0;
			}
		
			.serput {
				padding: 0 16rpx;
				width: 500rpx;
				font-size: 28rpx;
				color: #333333;
			}
		}
	}
	
	.custom-navbar{
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		padding: 10rpx 30rpx;
		box-sizing:border-box;
		padding-top: calc(var(--status-bar-height) + var(--window-top) + 10px);
		background: linear-gradient(to bottom, #C8FFF6, #fff);
		z-index: 999;
		
		.listtxt{
			font-size: 32rpx;
			font-weight: bold;
			letter-spacing: 0em;
			padding-bottom: 8rpx;
			color: #3D3D3D;
		}
		
		.top {
			display: flex;
			align-items: center;
		
			.dian {
				margin-left: 8px;
				width: 12rpx;
				height: 12rpx;
				border-radius: 50%;
				background: #45C4B0;
			}
			
			.txt {
				font-size: 20rpx;
				font-weight: normal;
				letter-spacing: 0em;
				padding-left: 8rpx;
				color: #45C4B0;
			}
			
			.dian2{
				margin-left: 8px;
				width: 12rpx;
				height: 12rpx;
				border-radius: 50%;
				background: #999;
			}
			.txt2{
				font-size: 20rpx;
				font-weight: normal;
				letter-spacing: 0em;
				padding-left: 8rpx;
				color: #999;
			}
		}
	}
	
	.tabbarActive {
		color: #3d3d3d !important;
	}
	
	.tabbar {
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 102rpx;
		background-color: #ffffff;
		z-index: 99;
		box-shadow: 0 0 3px #eeeeee;
		/* #ifdef APP */
		padding-bottom: calc(var(--window-bottom) + 18px);
		/* #endif */
		
	}
	
	.tabbar-item {
		text-align: center;
		width: 20%;
	}
	
	/* 选中后 */
	.item-img {
		width: 50rpx;
		height: 50rpx;
		margin: 0 auto;
	}
	
	/* 选中前 */
	.item-img1 {
		width: 50rpx;
		margin: 0 auto;
		height: 50rpx;
	}
	
	.itemtxt {
		font-size: 24rpx;
		color: #999999;
		margin-top: -10rpx;
	}
	
	.chat-num {
		position: absolute;
		left: 530rpx;
		top: 0;
		z-index: 99;
	}
</style>
